package com.su.sweet.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.su.sweet.model.SRoleMenu;
import com.su.sweet.mapper.SRoleMenuMapper;
import com.su.sweet.service.ISRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.noear.solon.annotation.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单关联 服务实现类
 * </p>
 *
 * @author su
 * @since 2025-01-02
 */
@Component
public class SRoleMenuServiceImpl extends ServiceImpl<SRoleMenuMapper, SRoleMenu> implements ISRoleMenuService {

    @Override
    public boolean updateRoleMenus(Long roleId, List<Long> menuIds, Long userId) {
        // 先删除该角色原有的菜单关联
        this.lambdaUpdate()
                .eq(SRoleMenu::getRoleId, roleId)
                .remove();

        // 批量插入新的菜单关联
        if (menuIds != null && !menuIds.isEmpty()) {
            List<SRoleMenu> roleMenus = menuIds.stream()
                    .map(menuId -> {
                        SRoleMenu roleMenu = new SRoleMenu();
                        roleMenu.setRoleId(roleId);
                        roleMenu.setMenuId(menuId);
                        roleMenu.setCreateTime(LocalDateTime.now());
                        roleMenu.setCreateUser(userId);
                        return roleMenu;
                    })
                    .collect(Collectors.toList());

            return this.saveBatch(roleMenus);
        }

        return true;
    }
}
